package com.ysd.lis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.toolkit.JoinWrappers;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.BaseEntity;
import com.ysd.lis.entity.SysUser;
import com.ysd.lis.entity.WkKnowledgeTestOption;
import com.ysd.lis.entity.WkKnowledgeTestQuestion;
import com.ysd.lis.mapper.WkKnowledgeTestOptionMapper;
import com.ysd.lis.mapper.WkKnowledgeTestQuestionMapper;
import com.ysd.lis.request.CreateSmallQuestionParam;
import com.ysd.lis.request.TestQuestionRequest;
import com.ysd.lis.service.WkKnowledgeTestOptionService;
import com.ysd.lis.service.WkKnowledgeTestQuestionService;
import com.ysd.util.RedisUserManager;
import com.ysd.util.ToolsUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author LuoXS
 * @date 2024/4/3
 * version 1.0
 */
@Service
@Slf4j
public class WkKnowledgeTestQuestionServiceImpl extends ServiceImpl<WkKnowledgeTestQuestionMapper, WkKnowledgeTestQuestion> implements WkKnowledgeTestQuestionService {

    @Autowired
    WkKnowledgeTestQuestionMapper mapper;

    @Autowired
    WkKnowledgeTestOptionService optionService;

    @Autowired
    WkKnowledgeTestOptionMapper optionMapper;


    @Override
    public Result add(WkKnowledgeTestQuestion params) {
        Result result = Result.succ(1, "添加成功！", null);
        try {
            SysUser sysUser = RedisUserManager.getUser();
            if (ToolsUtils.isNotEmpty(sysUser)) {
                params.setCreator(sysUser.getCreator());
//                params.setOrgId(sysUser.getOrgId());
            }
            boolean save = this.save(params);
            if (!save) {
                result = Result.fail("添加失败！");
            } else {
                List<WkKnowledgeTestOption> optionList = params.getOptionList();
                for (WkKnowledgeTestOption option : optionList) {
                    if (ToolsUtils.isNotEmpty(sysUser)) {
                        option.setCreator(sysUser.getCreator());
                    }
                    option.setQuestionId(params.getId());
                }
                boolean b = optionService.saveBatch(optionList);
                if (!b) {
                    result = Result.fail("添加失败！");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.fail("添加失败！");
        }
        return result;
    }

    @Override
    public Result pageList(TestQuestionRequest.PageListParam pageParam) {
        Result result;
        try {
            LambdaQueryWrapper<WkKnowledgeTestQuestion> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            Page<WkKnowledgeTestQuestion> page = new Page<>();
            page.setCurrent(pageParam.getPageIndex());
            page.setSize(pageParam.getPageSize());
            //参数
            if (!StringUtils.isEmpty(pageParam.getSearchValue())) {
                lambdaQueryWrapper.and(wrapper ->
                        wrapper.like(WkKnowledgeTestQuestion::getQuestionTitle, pageParam.getSearchValue()));
            }
            lambdaQueryWrapper.eq(StringUtils.isNotBlank(pageParam.getSearchType()), WkKnowledgeTestQuestion::getQuestionType, pageParam.getSearchType());
            lambdaQueryWrapper.eq(StringUtils.isNotBlank(pageParam.getKnowledgeId()), WkKnowledgeTestQuestion::getKnowledgeId, pageParam.getKnowledgeId());
            lambdaQueryWrapper.eq(StringUtils.isNotBlank(pageParam.getCatalogId()), WkKnowledgeTestQuestion::getCatalogId, pageParam.getCatalogId());

            lambdaQueryWrapper.eq(WkKnowledgeTestQuestion::getDelFlag, 0);
            lambdaQueryWrapper.orderByDesc(BaseEntity::getCreateTime);
            Page<WkKnowledgeTestQuestion> labInstrSetupPage = mapper.selectPage(page, lambdaQueryWrapper);
            result = Result.succ(labInstrSetupPage);
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.fail("查询失败！");
        }
        return result;

    }

    @Override
    public Result delete(TestQuestionRequest.DeleteParam params) {
        Result result;
        try {
            if (ToolsUtils.isEmpty(params) || ToolsUtils.isEmpty(params.getIds())) {
                return Result.fail("入参不可为空！");
            }
            String[] array = params.getIds().split(",");

            List<String> idList = Arrays.asList(array);
            LambdaQueryWrapper<WkKnowledgeTestOption> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(WkKnowledgeTestOption::getQuestionId, idList);
            int delete = optionMapper.delete(queryWrapper);
            if (delete > 0) {
                boolean b = this.removeByIds(Arrays.asList(array));
                if (b) {
                    result = Result.succ(1, "删除成功", null);
                } else {
                    result = Result.fail(400, "删除失败", "");
                }
            } else {
                result = Result.fail(400, "删除失败", "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.fail(400, "删除失败", "");
        }
        return result;
    }

    @Override
    public Result get(String id) {
        Result result;
        try {
            if (StringUtils.isBlank(id)) {
                return Result.fail("入参不可为空！");
            }
            LambdaQueryWrapper<WkKnowledgeTestQuestion> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BaseEntity::getId, id);
            queryWrapper.eq(BaseEntity::getDelFlag, false);
            WkKnowledgeTestQuestion testQuestion = mapper.selectOne(queryWrapper);
            List<WkKnowledgeTestOption> wkKnowledgeTestOptions = optionMapper.selectList(new LambdaQueryWrapper<WkKnowledgeTestOption>().eq(WkKnowledgeTestOption::getQuestionId, id).orderByAsc(BaseEntity::getCreateTime));

            List<WkKnowledgeTestOption> collect = wkKnowledgeTestOptions.stream().peek(x -> {
                x.setInputVisible(false);
                x.setDynamicTags(StringUtils.isNotBlank(x.getOptionKeyword()) ? Arrays.asList(x.getOptionKeyword().split(",")) : null);
            }).collect(Collectors.toList());

            testQuestion.setOptionList(collect);
            result = Result.succ(testQuestion);
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.fail(400, "查询失败", "");
        }
        return result;
    }

    @Override
    public Result edit(WkKnowledgeTestQuestion params) {
        Result result;
        try {
            SysUser sysUser = RedisUserManager.getUser();
            mapper.updateById(params);

            LambdaQueryWrapper<WkKnowledgeTestOption> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(WkKnowledgeTestOption::getQuestionId, params.getId());
            optionMapper.delete(queryWrapper);

            List<WkKnowledgeTestOption> optionList = params.getOptionList();
            for (WkKnowledgeTestOption option : optionList) {
                if (ToolsUtils.isNotEmpty(sysUser)) {
                    option.setCreator(sysUser.getCreator());
                }
                option.setQuestionId(params.getId());
            }
            optionService.saveOrUpdateBatch(optionList);
            result = Result.succ(1, "操作成功", null);

        } catch (Exception e) {
            e.printStackTrace();
            result = Result.fail(400, "操作失败", "");
        }
        return result;
    }

    @Override
    public List<WkKnowledgeTestQuestion> getQuestionByPaper(CreateSmallQuestionParam createSmallQuestionParam) {
        MPJLambdaWrapper<WkKnowledgeTestQuestion> lambdaWrapper = JoinWrappers.lambda(WkKnowledgeTestQuestion.class)
                .selectAll(WkKnowledgeTestQuestion.class)
                .selectCollection(WkKnowledgeTestOption.class, WkKnowledgeTestQuestion::getOptionList)
                .leftJoin(WkKnowledgeTestOption.class, WkKnowledgeTestOption::getQuestionId, WkKnowledgeTestOption::getId)
                .eq(WkKnowledgeTestQuestion::getQuestionType, createSmallQuestionParam.getQuestionType())
                .eq(WkKnowledgeTestQuestion::getDelFlag, 0)
                .in(WkKnowledgeTestQuestion::getCatalogId, createSmallQuestionParam.getKnowledgeIds());
        return mapper.selectJoinList(WkKnowledgeTestQuestion.class, lambdaWrapper);
    }
}
